package biznussoft.fieldservice360.fragments;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.MenuItemCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import biznussoft.fieldservice360.R;
import biznussoft.fieldservice360.adapter.ActivitesAdapter;
import biznussoft.fieldservice360.listeners.ActivityDetailListener;
import biznussoft.fieldservice360.listeners.GlobalListener;
import biznussoft.fieldservice360.model.ActivityModel;
import biznussoft.fieldservice360.model.ServiceOrderModel;
import biznussoft.fieldservice360.model.SiteInventoryModel;
import biznussoft.fieldservice360.utils.Session;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.salesforce.androidsdk.app.SalesforceSDKManager;

public class ServiceOrderDetailsFragment extends BaseFragment implements OnItemClickListener {
	 private LocationListener mLocationListener;
	 private LocationClient locationClient;
	 private String destinatioAddress;
	 private Double lat,lon;
	private TextView tvInstalledProducts,tvProductId,tvAgreementName,tvEntitledGroupName,tvServiceName,tvServicedescription,tvServiceOrderId,tvAccount,tvBillAdress,tvContact,tvSiteName,tvAdress,tvBillable,tvNoOfActivites,
	tvPhone,tvPriority,tvStatus,tvStartDate;
	private ListView lv,inventoryListView;
	static ArrayList<ActivityModel> list ;
	private GlobalListener listener;
	ActivityDetailListener listenerl;
	private ServiceOrderModel mobel;
	static ArrayList<SiteInventoryModel> inventoryList;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.serviceorder_details_fragment, null);
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);               
		setHasOptionsMenu(true);
	}
	
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		MenuItem addAccount = menu.add("GetDirection");
		MenuItemCompat.setShowAsAction(addAccount, MenuItemCompat.SHOW_AS_ACTION_ALWAYS | MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT);
		addAccount.setIcon(R.drawable.direction); 
		MenuItem actionItem = menu.add("Logout");                 
		MenuItemCompat.setShowAsAction(actionItem,MenuItemCompat.SHOW_AS_ACTION_ALWAYS | MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT);
		actionItem.setIcon(R.drawable.logout); 
		super.onCreateOptionsMenu(menu, inflater);
	}                         
	
	
	@Override
	 public boolean onOptionsItemSelected(MenuItem item) {
		 if(item.getTitle().equals("Logout")){
			 SalesforceSDKManager.getInstance().logout(getActivity());}
		 if(item.getTitle().equals("GetDirection")){
			 MyLocationManager loc = new MyLocationManager(getActivity());
			 loc.getLocations();
		 }
		
		 return super.onOptionsItemSelected(item);
	 }
	
	@Override
	public void onAttach(Activity activity) {          
		// TODO Auto-generated method stub
		super.onAttach(activity);
		listener = (GlobalListener) getActivity();
		listenerl = (ActivityDetailListener) getActivity();
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
	
		lv = (ListView) getView().findViewById(R.id.siteListview);
		lv.setOnItemClickListener(this);
		
		tvServiceOrderId = (TextView) getView().findViewById(R.id.tvorderid);
		tvSiteName = (TextView) getView().findViewById(R.id.tvSiteName);
		tvAccount = (TextView) getView().findViewById(R.id.tvAccount);
		tvBillAdress = (TextView) getView().findViewById(R.id.tvBilltoaddress);
		tvContact = (TextView) getView().findViewById(R.id.tvContact);
		tvAdress = (TextView) getView().findViewById(R.id.tvAddress);
		tvInstalledProducts = (TextView) getView().findViewById(R.id.tvInstalledProducts);
		tvAgreementName = (TextView) getView().findViewById(R.id.tvAgreement);
		tvEntitledGroupName = (TextView) getView().findViewById(R.id.tvEntitledGroup);
		tvServiceName = (TextView) getView().findViewById(R.id.tvServiceName);
		tvServicedescription = (TextView) getView().findViewById(R.id.tvServiceDescription);
		tvProductId = (TextView) getView().findViewById(R.id.tvAddress);
		tvBillable = (TextView) getView().findViewById(R.id.tvBillable);
		tvNoOfActivites = (TextView) getView().findViewById(R.id.tvNo_ofactivites);
		tvPhone = (TextView) getView().findViewById(R.id.tvPhone);
		tvPriority = (TextView) getView().findViewById(R.id.tvPriority);
		tvStatus = (TextView) getView().findViewById(R.id.tvStatus);
		tvStartDate = (TextView) getView().findViewById(R.id.tvStatDate);
		
	}
	
	
	public void getWarehouseDetails(int Position){      
		
		mobel = ServiceOrderFragment.serviceOrderList.get(Position);
		tvServiceOrderId.setText(mobel.getName());
		tvSiteName.setText(mobel.getSiteName());
		tvAccount.setText(mobel.getAccountName());
		tvBillAdress.setText(mobel.getBillToAddress());                   
		tvContact.setText(mobel.getContactName());
		destinatioAddress = mobel.getAddress();
		tvAdress.setText(destinatioAddress);
		tvBillable.setText(mobel.getBillable());
		tvNoOfActivites.setText(mobel.getActivities());
		tvPhone.setText(mobel.getAlternatePhone());
		tvPriority.setText(mobel.getPriority());
		tvStatus.setText(mobel.getStatus());
		tvStartDate.setText(mobel.getStartDate());
		tvInstalledProducts.setText(mobel.getInstallesProduct());
		tvProductId.setText(mobel.getProductId2());
		tvAgreementName.setText(mobel.getAgreementName());
		tvEntitledGroupName.setText(mobel.getEntitleGroupName());
		tvServiceName.setText(mobel.getServiceName());
		tvServicedescription.setText(mobel.getServiceDescription());
		list = ServiceOrderFragment.activityDetailsList.get(mobel.getId());
		ActivitesAdapter adapter = new ActivitesAdapter(getActivity(),list);
		lv.setAdapter(adapter);
		
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
		
		switch (arg0.getId()) {
		case R.id.siteListview:
			ActivityModel bean = list.get(position);
			Session.sActivityId = bean.getActivityName();
			listener.onGetContacts(position, mobel.getName());
			break;
		default:
			break;
		}
		
		
	}
	
	

	/*@Override
	public void onClick(View arg0) {
		 MyLocationManager loc = new MyLocationManager(getActivity());
		 loc.getLocations();
	}*/
	
	  class MyLocationManager implements OnConnectionFailedListener ,ConnectionCallbacks{
	    	public Location location;
	    	private Context mContext;
	    	
	    	public MyLocationManager(Context context) {

	    		mContext = context;
	    	}

	    	public void getLocations() {
	    				 locationClient = new LocationClient(mContext, this, this);
	    				 locationClient.connect();
	    			}

	    	public void onConnected(Bundle connectionHint) {
	    		
	    			LocationRequest lRequest = LocationRequest.create().setInterval(1000).setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
	    			 mLocationListener = new LocationListener() {
	    				
	    				public void onLocationChanged(Location location) {
	    					lat = location.getLatitude();
	    					lon = location.getLongitude();
	    					new MyAsynTask().execute();
	    				}
	    			};
	    			
	    			locationClient.requestLocationUpdates(lRequest, mLocationListener);
	    			
	    			
	    	}

	    	public void onDisconnected() {
	    		
	    	}

	    	public void onConnectionFailed(ConnectionResult result) {
	    		
	    	}
	    }
	
	
	  public class MyAsynTask extends AsyncTask<Void, Void, Void>{

			@Override
			protected Void doInBackground(Void... params) {
				  try {
					  getLocationInfo(lat, lon);
		            } catch (Exception e) {
		                e.printStackTrace();
		            }
				return null;
			}
	    	
	    }
	  
	  
	  public  JSONObject getLocationInfo(Double lat,Double lon) {

			HttpGet httpGet = new HttpGet("http://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+lon+"&sensor=false");
			HttpClient client = new DefaultHttpClient();
			HttpResponse response;
			StringBuilder stringBuilder = new StringBuilder();

			try {
				response = client.execute(httpGet);
				HttpEntity entity = response.getEntity();
				InputStream stream = entity.getContent();
				int b;
				while ((b = stream.read()) != -1) {
					stringBuilder.append((char) b);
				}
			} catch (ClientProtocolException e) {
			} catch (IOException e) {
			}

			JSONObject jsonObject = new JSONObject();
			
			try {
				jsonObject = new JSONObject(stringBuilder.toString());
				getGeoPoint(jsonObject);
			} catch (JSONException e) {
				Log.i("NCS", "Exception 1 is  :  " + e.getMessage());
			}
			                             
			
			return jsonObject;
		}
		
	  
	  public  void getGeoPoint(JSONObject jsonObject) {

			
			try {
				locationClient.removeLocationUpdates(mLocationListener);
				JSONArray results = jsonObject.getJSONArray("results");
				JSONObject js = results.getJSONObject(0);
				String adress = js.getString("formatted_address");

				/*String uri = "http://maps.google.com/maps?saddr="+adress+"&daddr="+"Begumpet, Hyderabad, Andhra Pradesh";
				 Intent i = new  Intent(Intent.ACTION_VIEW,Uri.parse("geo:0,0?q="+"Begumpet, Hyderabad, Andhra Pradesh"));       
				Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(uri));
				intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
				startActivity(i); */
				String uri = "http://maps.google.com/maps?saddr="+adress+"&daddr="+"Begumpet, Hyderabad, Andhra Pradesh";
				Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(uri));
				intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
				startActivity(intent);    
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}


		}

}
